import { createStore, Store, useStore as useVuexStore } from 'vuex'

import login from './login/login'
import system from './main/system/system'
import dashboard from './main/analysis/dashboard'

import { getPageListData } from '@/service/main/system/system'

import { IRootState, IStoreType } from './types'

const store = createStore<IRootState>({
  state() {
    return {
      name: 'kobe',
      entireDepartment: [],
      entireRole: [],
      entireMenu: []
    }
  },
  mutations: {
    saveEntireDepartment(state, departmentList) {
      state.entireDepartment = departmentList
    },
    saveEntireRole(state, roleList) {
      state.entireRole = roleList
    },
    saveEntireMenu(state, menuList) {
      state.entireMenu = menuList
    }
  },
  actions: {
    async getInitialDataAction({ commit }) {
      // 1.请求部门数据
      const departmentResult = await getPageListData('/department/list', {
        offset: 0,
        size: 1000
      })
      // 起别名
      const { list: departmentList } = departmentResult.data

      // 2.请求角色数据
      const roleResult = await getPageListData('/role/list', {
        offset: 0,
        size: 1000
      })
      const { list: roleList } = roleResult.data

      // 3.将数据提交到mutations
      commit('saveEntireDepartment', departmentList)
      commit('saveEntireRole', roleList)

      // 4.请求角色菜单列表
      const menuResult = await getPageListData('/menu/list', {})
      const { list: menuList } = menuResult.data
      commit('saveEntireMenu', menuList)
    }
  },
  modules: {
    login,
    system,
    dashboard
  }
})

// 1.从新初始化store的数据
// 每次只要进行刷新,vuex里的数据会被清除
// 在main.ts里调用
export function setupStore() {
  store.dispatch('login/loadLocalLogin')
}

// 2.给useStore扩展类型
export function useStore(): Store<IStoreType> {
  return useVuexStore()
}

export default store
